const db = require("../db")

// 登录处理函数
exports.login = (req, res) => {
  const userinfo = req.body
  const nature = `Login('${userinfo.username}', '${userinfo.password}', '${userinfo.identity}')`
  const sql = `select ${nature};`
  db.query(sql, function (err, results) {
    if (err) return res.cc({msg: err.sqlMessage})
    if (results[0][nature]) return res.cc({ msg: '登录成功!' }, 200)
    res.cc({ msg: '登录失败!' })
  })
}

// 修改密码处理函数
exports.updatepwd = (req, res) => {
  const userinfo = req.body
  const nature = `Updatepwd('${userinfo.username}', '${userinfo.old}', '${userinfo.new}', '${userinfo.identity}')`
  const sql = `select ${nature};`
  db.query(sql, function (err, results) {
    if (err) return res.cc({msg: err.sqlMessage})
    if (results[0][nature]) return res.cc({ msg: '修改成功!' }, 200)
    res.cc({ msg: '修改失败!' }, 400)
  })
}

// 查找用户姓名
exports.username = (req, res) => {
  const userinfo = req.body
  const nature = `Username('${userinfo.username}', '${userinfo.identity}')`
  const sql = `select ${nature};`
  db.query(sql, function (err, results) {
    if (err) return res.cc({msg: err.sqlMessage})
    const username = results[0][nature]
    if (username) return res.cc({ msg: '查找成功!', username }, 200)
    res.cc({ msg: '查找失败!' }, 400)
  })
}

// 查看所有课程
exports.allcourse = (req, res) => {
  const sql = `select * from sc5342.all_course_view order by c_semeter, c_type desc, c_no, t_no;`
  db.query(sql, function (err, results) {
    if (err) return res.cc({msg: err.sqlMessage})
    let i = 0
    let repeat = false
    while (i<results.length) {
      repeat = false
      if (!results[i].c_type) {
        results[i].class_no = ''
      }
      results[i].c_type= results[i].c_type ? '必修' : '选修'
      results[i].c_semeter= results[i].c_semeter==1 ? '上半学年' : '下半学年'
      for (let k=0; k<i; k++) {
        if (results[i].c_no == results[k].c_no && results[i].c_semeter === results[k].c_semeter) {
          if (results[i].t_no !== results[k].t_no) {
            results[k].t_name += ', ' +  results[i].t_name
          }
          if (results[i].class_no !== results[k].class_no && results[i].c_type === '必修') {
            results[k].class_no += ', ' +  results[i].class_no
          }
          results.splice(i,1)
          repeat = true
          break
        }
      }
      if (!repeat) i++;
    }
    res.cc(results, 200)
  })
}
